﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;

namespace AppTouchScreen.Imaging
{
    /// <summary>
    /// Encapsulate work with a image
    /// </summary>
    [Serializable]
    public class ImageInfo
    {

        #region Data

        /// <summary>
        /// Path to the image file
        /// </summary>
        private readonly string _path = "";

        /// <summary>
        /// The name of the image folder
        /// </summary>
        private const string ImegFolder = "images";

        /// <summary>
        /// Reference on all loaded image
        /// </summary>
        private static readonly ObservableCollection<ImageInfo> AllBitmaps = new ObservableCollection<ImageInfo>();

        #endregion

        #region Constructors

        private ImageInfo(){}

        public ImageInfo(int id)
        {
            FileInfo file = null;
            var di = new DirectoryInfo(ImageFolderPath);
            var files = di.GetFiles(id.ToString() + ".*");
            if (files.Count() > 0)
            {
                file = files[0];
#if PORTABLEAPP
                _path = ImegFolder + Path.DirectorySeparatorChar + file.Name;
#else
                _path = file.FullName;

#endif
            }
            else
            {
                throw new Exception("Not found id " + id.ToString());
            }
            AllBitmaps.Add(this);
        }

        #endregion //Constructors

        #region Static methods

        /// <summary>
        /// Create ImageInfo from path to image
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static ImageInfo CreateImageInfo(string path)
        {
            ImageInfo bitmapId = null;
            int id = GetLastId();
            if (File.Exists(path))
            {
                File.Copy(path, ImageFolderPath +
                                Path.DirectorySeparatorChar + id.ToString()
                                + Path.GetExtension(path));

                bitmapId = new ImageInfo(id);
            }
            return bitmapId;
        }

        /// <summary>
        /// Delete not using image from the folder
        /// </summary>
        public static void ClearNotUsing()
        {
            var di = new DirectoryInfo(ImageFolderPath);
            //List<FileInfo> remFiles = new List<FileInfo>();
            var files = di.GetFiles();
            foreach (var file in files)
            {
                bool exist = false;

                foreach (var bitmapId in AllBitmaps)
                {
                    string actualFilePath = "";
#if PORTABLEAPP
                    actualFilePath = ImegFolder + Path.DirectorySeparatorChar + file.Name;

#else
                    actualFilePath = file.FullName;


#endif
                    if (bitmapId._path == actualFilePath)
                    {
                        exist = true;
                    }
                }

                if (!exist)
                {
                    try
                    {
                        file.Delete();
                    }
                    finally
                    {
                    }
                }
            }

        }

        /// <summary>
        /// Get last id from image folder, id init from file name
        /// </summary>
        /// <returns></returns>
        private static int GetLastId()
        {
            int lastId = 0;
            var di = new DirectoryInfo(ImageFolderPath);
            FileInfo[] files = di.GetFiles();
            var filesEnum = files.AsEnumerable();
            var fs = from c in filesEnum orderby Convert.ToInt32(Path.GetFileNameWithoutExtension(c.Name)) select c;
            if (fs.Count() > 0)
            {
                int.TryParse(Path.GetFileNameWithoutExtension(fs.Last().Name), out lastId);
                lastId++;
            }
            return lastId;
        }

        #endregion //Static methods

        #region Properties

        /// <summary>
        /// Return BitmapImage for this ImageInfo 
        /// </summary>
        public BitmapImage BitmapImage
        {
            get
            {

#if PORTABLEAPP
                return new BitmapImage(new Uri(ImageFolderPath +
                    Path.DirectorySeparatorChar + Path.GetFileName(_path), UriKind.Absolute));


#else
                return new BitmapImage(new Uri(_path, UriKind.Absolute));


#endif
            }
        }

        /// <summary>
        /// The path to image folder
        /// </summary>
        private static string ImageFolderPath
        {
            get
            {

#if PORTABLEAPP
                string appPath = Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().Location);
                FileInfo fi = new FileInfo(appPath);

                string dirPath = fi.Directory.FullName + Path.DirectorySeparatorChar + ImegFolder;

                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                return dirPath;
#else
                string appName = Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location);

                string dir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
                             + Path.DirectorySeparatorChar + appName + 
                             Path.DirectorySeparatorChar + ImegFolder;

                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                return dir;
#endif

            }
        }

        #endregion //Properties

    }
}
